{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Cross-Resonance 门\n",
    "\n",
    "*版权所有 (c) 2021 百度量子计算研究所，保留所有权利。*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 内容概要\n",
    "\n",
    "本教程介绍如何使用量脉生成 Cross-Resonance（CR）门的优化脉冲序列。与之前教程中的 iSWAP 和 CZ 门的实现不同，CR 门是使用全微波驱动实现的。本教程的概要如下：\n",
    "\n",
    "- 背景介绍\n",
    "- 准备工作\n",
    "- 构造哈密顿量\n",
    "- 通过量脉云服务生成与优化脉冲\n",
    "- 总结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 背景介绍\n",
    "\n",
    "**基本原理**\n",
    "\n",
    "与我们之前介绍的量子门不同的是，CR 门只使用微波来实现两个量子比特的相互作用，这样我们就可以避免由磁通而引起的噪声。CR 门的物理实现涉及两个耦合的频率固定的量子比特，并且使驱动脉冲的频率等于目标量子比特（Target Qubit）的频率，如下图所示：\n",
    "\n",
    "\n",
    "![cr-circuit](figures/cr-circuit.png)\n",
    "\n",
    "\n",
    "我们先关注系统的有效哈密顿量（详见参考文献 \\[1\\]）。在双旋转坐标系中，我们用驱动强度 $A$、失谐量 $\\Delta$、驱动相位 $\\phi_0$ 和耦合强度 $g_{01}$ 表示 cross-resonance 效应的有效哈密顿量（为了简洁，我们令 $\\hbar=1$）：\n",
    "\n",
    "$$\n",
    "\\hat{H}_{\\rm eff} = \\frac{A}{4\\Delta}g_{01}(\\hat{\\sigma}_0^z\\hat{\\sigma}_1^x\\cos{\\phi_0}+\\hat{\\sigma}_0^z\\hat{\\sigma}_1^y\\sin{\\phi_0}).\n",
    "$$\n",
    "\n",
    "当 $\\phi_0=0$ 时，cross-resonance 效应产生了 $\\hat{\\sigma}^z_0\\otimes\\hat{\\sigma}_1^x$ 有效耦合。因此，我们可以从上面的有效哈密顿量推导出时间演化算符：\n",
    "\n",
    "$$\n",
    "U_{\\rm CR}(\\theta)=e^{-i\\frac{\\theta}{2}\\hat{\\sigma}^z_0\\otimes\\hat{\\sigma}^x_1},\n",
    "$$\n",
    "\n",
    "其中 $\\theta=\\Omega_0 g_{01}t/(2\\Delta)$（$t$ 是门时间）。可见，cross-resonance 效应使得量子比特 $q_1$（目标量子比特）的旋转取决于量子比特 $q_0$（控制量子比特）的状态。\n",
    "\n",
    "\n",
    "\n",
    "通过上面的推导, CR 门的矩阵形式是（有关更多详细信息，请参阅 \\[2\\]）：\n",
    "$$\n",
    "U_{\\rm CR}(\\theta) = \\begin{bmatrix} \n",
    "\\cos{\\frac{\\theta}{2}} & -i\\sin{\\frac{\\theta}{2}} & 0 & 0 \\\\\n",
    "-i\\sin{\\frac{\\theta}{2}} & \\cos{\\frac{\\theta}{2}} & 0 & 0 \\\\ \n",
    "0 & 0 & \\cos{\\frac{\\theta}{2}} & i\\sin{\\frac{\\theta}{2}} \\\\\n",
    "0 & 0 & i\\sin{\\frac{\\theta}{2}} & \\cos{\\frac{\\theta}{2}} \n",
    "\\end{bmatrix}.\n",
    "$$\n",
    "\n",
    " \n",
    "特别的，当 $\\theta=-\\frac{\\pi}{2}$ 时，CR 门的矩阵表示为：\n",
    "\n",
    "$$\n",
    "U_{\\rm CR}(-\\pi/2) = \\frac{\\sqrt{2}}{2} \n",
    "\\begin{bmatrix}\n",
    "1 & i & 0 & 0 \\\\\n",
    "i & 1 & 0 & 0 \\\\\n",
    "0 & 0 & 1 & -i \\\\\n",
    "0 & 0 & -i & 1\n",
    "\\end{bmatrix}.\n",
    "$$\n",
    "\n",
    "**应用**\n",
    "\n",
    "在分析了实现 CR 门的一些基本原理之后，我们现在关注 CR 门在量子计算中的应用：其中之一是通过增加两个额外的单量子比特门来实现 CNOT 门。\n",
    "\n",
    "![cr-note](figures/cr-gate.png) \n",
    "\n",
    "在本教程中，我们对由两个三能级的量子比特组成的系统进行建模，并以目标量子比特（量子比特 $q_1$）的频率向控制量子比特（量子比特 $q_0$）施加驱动脉冲。通过旋转波近似（RWA），哈密顿量可以表示为（更多细节请参阅 \\[1\\]）：\n",
    "\n",
    "$$\n",
    "\\hat{H}_{\\rm sys} = (\\omega_{\\rm q0}-\\omega_{\\rm d})\\hat{a}_{0}^{\\dagger }\\hat{a}_0 + (\\omega_{\\rm q1}-\\omega_{\\rm d})\\hat{a}_1^\\dagger \\hat{a}_1 + \\frac{\\alpha_0}{2} \\hat{a}^{\\dagger2}_0\\hat{a}^2_0 + \\frac{\\alpha_1}{2} \\hat{a}^{\\dagger2}_1\\hat{a}^2_1+\\frac{g}{2}(\\hat{a}_0\\hat{a}_1^\\dagger + \\hat{a}_0^\\dagger\\hat{a}_1) + \\Omega_0^x(t)\\frac{\\hat{a}^\\dagger_0+\\hat{a}_0}{2}.\n",
    "$$\n",
    "\n",
    "其中各种符号定义见下表：\n",
    "\n",
    "\n",
    "|符号|定义|\n",
    "|:--------:|:----------:|\n",
    "|$\\omega_{\\rm qi}$| 量子比特 $q_i$ 的频率|\n",
    "|$\\omega_{\\rm d}$|驱动频率|\n",
    "|$\\hat{a}_i^{\\dagger}$|产生算符|\n",
    "|$\\hat{a}_i$|湮灭算符|\n",
    "|$\\alpha_i$| 量子比特 $q_i$ 的非谐性|\n",
    "|$g$|耦合强度|\n",
    "|$\\Omega_0^x$(t)| X 通道的脉冲函数|"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 准备工作\n",
    "\n",
    "成功安装量脉后，您可以按照本教程运行下面的量脉程序。要运行此教程，您需要从量脉（Quanlse）和其它常用的 Python 库导入以下包："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import Hamiltonian-related module\n",
    "from Quanlse.QHamiltonian import QHamiltonian as QHam\n",
    "from Quanlse.QOperator import driveX, number, duff\n",
    "\n",
    "# Import optimizer for the cross-resonance gate\n",
    "from Quanlse.remoteOptimizer import remoteOptimizeCr\n",
    "\n",
    "# Import tools to analyze the result\n",
    "from Quanlse.Utils.Functions import project\n",
    "from Quanlse.Utils.Infidelity import unitaryInfidelity\n",
    "\n",
    "# Import numpy and math\n",
    "from numpy import round\n",
    "from math import pi"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 构造哈密顿量\n",
    "\n",
    "\n",
    "现在，我们需要使用量脉来构造哈密顿量。在量脉中，所有关于哈密顿量的信息都存储在一个字典中。我们首先定义一些构造哈密顿量的字典所需的基本参数：采样周期、系统中的量子比特数量和系统的能级。为了初始化该哈密顿量的字典，我们从模块 `QHamiltonian` 调用函数 `QHamiltonian()`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Sampling period\n",
    "dt = 1.0\n",
    "\n",
    "# Number of qubits\n",
    "qubits = 2\n",
    "\n",
    "# System energy level\n",
    "level = 3\n",
    "\n",
    "# Initialize the Hamiltonian\n",
    "ham = QHam(subSysNum=qubits, sysLevel=level, dt=dt)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在我们可以开始构造哈密顿量了。在开始之前，我们需要定义几个常量作为函数的参数："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Parameters setting  \n",
    "qubitArgs = {\n",
    "    \"coupling\": 0.0038 * (2 * pi),  # Coupling of Q0 and Q1\n",
    "    \"qubit_freq0\": 5.114 * (2 * pi),  # Frequency of Q0\n",
    "    \"qubit_freq1\": 4.914 * (2 * pi),  # Frequency of Q1\n",
    "    \"drive_freq0\": 4.914 * (2 * pi),  # Drive frequency on Q0\n",
    "    \"drive_freq1\": 4.914 * (2 * pi),  # Drive frequency on Q1\n",
    "    \"qubit_anharm0\": -0.33 * (2 * pi),  # Anharmonicity of Q0\n",
    "    \"qubit_anharm1\": -0.33 * (2 * pi)  # Anharmonicity of Q1\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后我们需要在之前初始化的哈密顿的字典中添加以下项：\n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "\\hat{H}_{\\rm drift} &= (\\omega_{\\rm q0}-\\omega_{\\rm d}) \\hat{a}_0^\\dagger \\hat{a}_0 + (\\omega_{\\rm q1}-\\omega_{\\rm d}) \\hat{a}_1^\\dagger \\hat{a}_1 + \\frac{\\alpha_0}{2} \\hat{a}_0^{\\dagger}\\hat{a}_0^{\\dagger}\\hat{a}_0 \n",
    "\\hat{a}_0 + \\frac{\\alpha_1}{2} \\hat{a}_1^{\\dagger}\\hat{a}_1^{\\dagger}\\hat{a}_1 \\hat{a}_1 , \\\\\n",
    "\\hat{H}_{\\rm coup} &= \\frac{g_{01}}{2}(\\hat{a}_0 \\hat{a}_1^\\dagger+\\hat{a}^\\dagger_0 \\hat{a}_1). \\\\\n",
    "\\end{align}\n",
    "$$\n",
    "\n",
    "在量脉的 `Operator` 模块中，我们提供了一些允许用户快速构造常用算符的工具。失谐项 $(\\omega_{\\rm q}-\\omega_{\\rm d})\\hat{a}^\\dagger\\hat{a}$ 和非谐项 $\\frac{\\alpha}{2}\\hat{a}^\\dagger\\hat{a}^\\dagger\\hat{a}\\hat{a}$ 可以分别使用 `Operator` 模块中的 `number(n)` 和 `duff(n)` 生成：这两个函数 `number(n)` 和 `duff(n)` 分别返回 $n\\times n$ 的粒子数算符和 Duffing 算符。耦合项的形式为 $\\frac{g}{2}(\\hat{a}_i^\\dagger\\hat{a}_j+\\hat{a}_i\\hat{a}_j^\\dagger)$，可以使用函数 `addCoupling()` 直接添加到哈密顿量中。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Add the detuning and the anharmonicity terms\n",
    "for qu in range(2):\n",
    "    # Add the detuning term(s).\n",
    "    ham.addDrift(number, qu, (qubitArgs[f\"qubit_freq{qu}\"] - qubitArgs[f\"drive_freq{qu}\"]))\n",
    "    # Add the anharmonicity term(s).\n",
    "    ham.addDrift(duff, qu, qubitArgs[f\"qubit_anharm{qu}\"] / 2)\n",
    "\n",
    "# Add the coupling term\n",
    "ham.addCoupling([0, 1], qubitArgs[\"coupling\"] / 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "需要注意的是，量脉的优化函数会自动添加控制项：\n",
    "\n",
    "$$\n",
    "\\hat{H}_{\\rm ctrl}(t) = \\Omega_0^x(t)\\frac{\\hat{a}^\\dagger_0+\\hat{a}_0}{2},\n",
    "$$\n",
    "\n",
    "所以我们不需要手动添加这项。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "系统的哈密顿量构造完成后，我们可以进行量子系统的模拟。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 通过量脉云服务生成与优化脉冲"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在本地设备上处理优化过程通常需要很长时间，而我们提供的云服务可以显著加速此过程。要使用量脉云服务，用户需要从 http://quantum-hub.baidu.com 获取 token。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import tools to get access to cloud service\n",
    "from Quanlse import Define\n",
    "\n",
    "# To use remoteOptimizerCr on cloud, paste your token (a string) here\n",
    "Define.hubToken = ''"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为了找到 CR 门的优化脉冲，我们使用函数 `remoteOptimizeCr()`。 此函数以我们先前定义的哈密顿量、振幅的界、门的持续时间、最大迭代次数和目标失真度。通过调用 `remoteOptimizeCr()`，用户可以向量脉云服务提交优化任务。如果用户想要进一步减少失真度，我们建议用户尝试增加门时间 `tg`（CR 门的持续时间约为 200 到 400 纳秒）。用户还可以通过设置更大的 `aBound` 和 `maxIter` 来增大搜索空间。\n",
    "\n",
    "在本教程中，用来评估生成的量子门性能的失真度为 ${\\rm infid} = 1 - \\frac{1}{d}\\left|{\\rm Tr}[U^\\dagger_{\\rm goal}P(U)]\\right|$，其中 $U_{\\rm goal}$ 是目标酉变换 $U_{\\rm CR}(-\\pi /2)$，$d$ 是 $U_{\\rm goal}$ 的维度，$U$ 是前面定义的三级体系的实际酉演化。注意，$P(U)$ 描述投影到计算子空间的演化。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Set amplitude bound\n",
    "aBound = (-1.0, 3.0)\n",
    "\n",
    "# Run the optimization\n",
    "gateJob, infidelity = remoteOptimizeCr(ham, aBound=aBound, tg=200, maxIter=5, targetInfidelity=0.005)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们可以使用 `plot()` 可视化生成的脉冲。有关 `plot()` 的详细信息，请参考 [single-qubit-gate](https://quanlse.baidu.com/#/doc/tutorial-single-qubit)。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# Print waves and the infidelity\n",
    "gateJob.plot()\n",
    "print(f'infidelity: {infidelity}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用函数 `simulate()` 以及 `project()`，用户可以获得系统投影到计算子空间的演化后的矩阵 $P(U)$。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Print the system's evolution\n",
    "result = ham.simulate(job=gateJob)\n",
    "process2d = project(result[0][\"unitary\"], qubits, level, 2)\n",
    "print(\"The projected evolution P(U):\\n\", round(process2d, 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "此外，如果想要获取生成脉冲的每个时刻 `dt` 的数值，可以使用函数 `getPulseSequences()`。该函数采用哈密顿的字典和脉冲的通道名称作为输入参数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gateJob.generatePulseSequence(driveX(3), 0)\n",
    "gateJob.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 总结\n",
    "\n",
    "\n",
    "通过构造系统哈密顿量并在量脉云服务上产生优化的脉冲，我们成功地设计了一个可以实现高保真度的 cross-resonance 门的脉冲。用户可以通过点击这个链接 [tutorial-cr-gate.ipynb](https://github.com/baidu/Quanlse/blob/main/Tutorial/CN/tutorial-cr-cn.ipynb) 跳转到此 Jupyter Notebook 文档相应的 GitHub 页面并且运行这个程序。我们鼓励用户尝试不同于本教程的参数值以获得最佳结果。"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "source": [
    "## 参考文献\n",
    " \n",
    "\\[1\\] [Rigetti, Chad, and Michel Devoret. \"Fully microwave-tunable universal gates in superconducting qubits with linear couplings and fixed transition frequencies.\" *Physical Review B* 81.13 (2010): 134507.](https://journals.aps.org/prb/abstract/10.1103/PhysRevB.81.134507)\n",
    "\n",
    "\\[2\\] [Nielsen, Michael A., and Isaac L. Chuang. Quantum Computation and Quantum Information: 10th Anniversary Edition. Cambridge University Press, 2010.](http://csis.pace.edu/~ctappert/cs837-19spring/QC-textbook.pdf)"
   ],
   "execution_count": null,
   "outputs": []
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "6ad73c40f4f7e139e51b4243fd18c81784a68c09ce49361ba281b37d203f3e8e"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}